package com.by.impl;

import com.by.domain.Product;
import com.by.jdbc.ByJdbcFactory;
import com.by.jdbc.ByJdbcUtil;
import com.by.mapper.ProductInterface;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>数据库操作类<p/>
 *
 * @author boyin
 * @ClassName ProductInterfaceImpl
 * @Description 商品数据库实现类
 * @date 2024/11/8 7:30
 */
public class ProductInterfaceImpl implements ProductInterface {
    private Connection connection;
    private Statement statement;
    private  ResultSet resultSet;

    public ProductInterfaceImpl() {
        try {
            connection = ByJdbcFactory.getInstance().getJdbcUtil("H2").getConnection();
            statement = connection.createStatement();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Product> searchAllProduct() throws SQLException {
        if (connection == null)
            throw new RuntimeException("please new impl");

        resultSet = statement.executeQuery("select  * from PRODUCT");
        List<Product> products = new ArrayList<>();
        while (resultSet.next()) {
            Product product = new Product();
//            product.setId(resultSet.getString(1));
//            product.setName(resultSet.getString(2));
//            product.setStock(resultSet.getInt(3));
            product.setId(resultSet.getString("id"));
            product.setPrice(resultSet.getInt("price"));
            product.setStock(resultSet.getInt("stock"));
            product.setName(resultSet.getString("name"));
            products.add(product);
        }

        return products;
    }

    @Override
    public boolean addProduct(Product product) {


        try {
            String sql = "INSERT INTO PRODUCT (id, name, stock,price) VALUES (?,?,?,?);";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, product.getId());
            preparedStatement.setString(2, product.getName());
            preparedStatement.setInt(3,product.getStock());
            preparedStatement.setInt(4,product.getPrice());
            return preparedStatement.executeLargeUpdate() > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
